package com.gree.shyun.server.fiddler;

import com.gree.shyun.bean.UrlSpit;
import com.gree.shyun.server.db.DbHelper;
import com.gree.shyun.server.db.util.LogUtils;
import com.gree.shyun.entity.ApiAction;
import com.gree.shyun.entity.ApiGroup;
import com.gree.shyun.util.*;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class GetApiByFiddler {

    /**
     * 保存所有api
     * @param resRoot
     * @param zipPath
     * @throws IOException
     */
    public static void saveAllApis(String resRoot,String zipPath) throws  IOException{
            String tempPath = resRoot+"tmp";
            ZipUtil.unZip(zipPath,tempPath);
            String filename = FileUtil.getFilename(zipPath);
            String pid = MD5.encrypt(filename);
            List<ApiAction> apiInfoList = getApiInfos(tempPath,pid);
            DbHelper.saveOrUpdate(apiInfoList);
            ApiGroup apiGroup = new ApiGroup();
            apiGroup.setId(pid);
            apiGroup.setName(filename);
            apiGroup.setDomainMd5(pid);
            apiGroup.setDomain(filename);
            DbHelper.saveOrUpdate(apiGroup);
            FileUtil.removeDir(tempPath);
    }
    /**
     * 获取APIs
     * @param root
     * @return
     */
    public static List<ApiAction> getApiInfos(String root,String pid){
        List<ApiAction> apiInfos = new ArrayList<>();
        int count  = FileUtil.getFileCount(root+"/raw")/3;
        int i = 1 ;
        boolean loop = true;
        while (loop){
            String request = getRaw(count,root,i,true);
            String respone = getRaw(count,root,i,false);
            LogUtils.e(request+"/"+respone);
            ApiAction apiInfo = getApiInfo(request,respone);
            if(apiInfo==null){
                loop = false;
                break;
            }
            apiInfo.setPid(pid);
            apiInfos.add(apiInfo);
            i++;
        }
        return apiInfos;
    }

    /**
     *  解析抓包数据
     * @param request
     * @param respone
     * @return
     */
    public static ApiAction getApiInfo(String request,String respone){
        ApiAction apiInfo = new ApiAction();
        if(request!=null) {
            String[] resuests = request.split("\n");
            if (resuests.length > 0) {
                String[] url = resuests[0].split(" ");
                if (url.length > 2) {
                    apiInfo.setMethod(url[0].toLowerCase());
                    String path = url[1];
                    String domain = null;
                    String split = "/api/";
                    if(path.contains(split)){
                        path = path.substring(path.indexOf(split));
                        int index = path.lastIndexOf(split)+1;
                        domain = path.substring(0,index-1);
                        path = path.substring(index);
                    }else{
                        try {
                            URL u = new URL(path);
                            domain = u.getHost();
                            path = path.substring(domain.length());
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                    }
                    UrlSpit urlSpit = CommonUtil.getUrlSpit(path);
                    apiInfo.setDomain(domain);
                    apiInfo.setDomainMd5(MD5.encrypt(urlSpit.getDomain()));
                    apiInfo.setUrl(urlSpit.getUrl());
                    apiInfo.setId(MD5.encrypt(urlSpit.getUrl()));
                    apiInfo.setUrlParam(urlSpit.getParam());
                    apiInfo.setAlias(urlSpit.getAlias());
                }
            }
            String r = getLastNLine(resuests);
            if (r != null && r.length() > 1) {
                //不是json格式转json
                if (!r.startsWith("{")) {
                    r = CommonUtil.urlParmToJson(r);
                }
                apiInfo.setRequest(r);
            }
        }
        if(respone!=null) {
            String[] respones = respone.split("\n");
            String res = getLastNLine(respones);
            if (res != null) {
                apiInfo.setRespone(res);
            }
        }
       return apiInfo.getId()==null?null:apiInfo;
    }

    /**
     *  获取空行开始的最后一行
     * @param res
     * @return
     */
    public static String getLastNLine(String[] res){
        String line = res[res.length-1];
        line = line.replaceAll("\n|\r","");
        return line;
    }
    /**
     * 获取raw文件
     * @param root
     * @param position
     * @param isRequest
     * @return
     */
    public static String getRaw(int count,String root,int position,boolean isRequest){
        String p=String.valueOf(position);
        if(count>=10&&position<10){
            p="0"+position;
        }
        String path = root+"/raw/"+p+"_"+(isRequest?"c":"s")+".txt";
        try {
            return JsonXmlUtils.fileToString(path);
        } catch (IOException e) {
          System.out.println("加载完毕。");
        }
        return null;
    }
}
